<?php
namespace Home\Controller;
use Home\Common\Controller\HomeController;
use Common\Api\WebSocket;
class WebSocketController extends HomeController {
	private $webSocketServer;
	private $model_message;
	
	/**
	 * 启动socket
	 */
	public function index(){
		
		echo 'webSocketServer Strar';
		
		// 创建数据模型和websocket实例
		$this -> model_message = D('public_message');
		$this -> webSocketServer = new \Common\Api\WebSocket();
		
		
		// 绑定回调函数到class mtahod;
		$this -> webSocketServer -> bind('message', function($clientID, $message, $messageLength, $binary){
			$this -> onMessage($clientID, $message, $messageLength, $binary);
		});
		$this -> webSocketServer -> bind('open', function($clientID){
			$this -> onOpen($clientID);
		});
		$this -> webSocketServer -> bind('close', function($clientID, $status){
			$this -> onClose($clientID, $status);
		});
		
		// 启动websocket服务，服务运行就阻塞在这里了
		$serverStatus = $this -> webSocketServer -> wsStartServer('0.0.0.0', 9300);
		echo 'over';
		//判断服务是否正常结束
		if($serverStatus == false){
			echo $this -> webSocketServer -> error;
		}else{
			echo 'webSocketServer Normal end';
		}
	}
	
	
	/**
	 * 收到信息
	 * @param unknown $clientID
	 * @param unknown $message
	 * @param unknown $messageLength
	 * @param unknown $binary
	 */
	function onMessage($clientID, $message, $messageLength, $binary){
		
		$ip = long2ip( $this -> webSocketServer->wsClients[$clientID][6] );
		
		if ( sizeof($this -> webSocketServer->wsClients) == 1 ){
			$this -> webSocketServer->wsSend($clientID, "服务器目前没有人在线，不过我还是会听你讲话--------你忠诚的服务器");
		}else{
			foreach ( $this -> webSocketServer->wsClients as $id => $client )
			if ( $id != $clientID ){
				$this -> webSocketServer->wsSend($id, "Visitor $clientID ($ip) said \"$message\"");
			}
		}
	}
	/**
	 * 客户连接
	 * @param unknown $clientID
	 */
	function onOpen($clientID){
		
	}
	/**
	 * 客户断开
	 * @param unknown $clientID
	 * @param unknown $status
	 */
	function onClose($clientID, $status){
		
	}
	
	

}